package com.ncloud.crm.service.impl;

import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.ncloud.crm.common.Constant;
import com.ncloud.crm.entity.BsProduct;
import com.ncloud.crm.mapper.BsProductMapper;
import com.ncloud.crm.utils.DateUtils;
import com.ncloud.param.service.SequenceService;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ncloud.common.enmus.ResultEnum;
import com.ncloud.common.exception.UserException;
import com.ncloud.crm.entity.order.OrderProduct;
import com.ncloud.crm.mapper.OrderProductMapper;
import com.ncloud.crm.service.OrderProductService;
import com.ncloud.crm.utils.OrderNodeDefineUtils;
import com.ncloud.crm.utils.TableIdDefineUtils;

@Service
public class OrderProductServiceImpl implements OrderProductService {
	
	private static final Logger logger = LogManager.getLogger(OrderProductServiceImpl.class);
	
	@Autowired
	private OrderProductMapper productMapper;
	@Autowired
	private BsProductMapper bsProductMapper;
	@Reference
	private SequenceService sequenceService;


	public List<OrderProduct> getByOrderId(Long orderId){
		List<OrderProduct> orderProducts = productMapper.getProductByOrderId(orderId);
		return orderProducts;
	}

	@Override
	public JSONObject getPk(JSONObject json) {
		return null;
	}

	@Override
	public JSONObject insert(JSONObject json) {

		OrderProduct orderProduct = JSON.parseObject(json.toJSONString(),OrderProduct.class);
		try {
			validation(orderProduct);
			productMapper.insertOrderProduct(orderProduct);
		}catch (RuntimeException e){
			e.printStackTrace();
			throw new UserException(ResultEnum.DATABASE_ERROR);
		}
		return json;
	}

	@Override
	public JSONObject validate(JSONObject json,JSONObject result) {
		JSONObject jsonObject = new JSONObject();
		JSONArray productArray = new JSONArray();
		Date currentDate = new Date();
		if(json == null){
			throw new UserException(ResultEnum.ORDER_INFO_ERROR);
		}
		if(json.containsKey(OrderNodeDefineUtils.ORDER_PRODUCT)){
			jsonObject = json.getJSONObject(OrderNodeDefineUtils.ORDER_PRODUCT);
			/*当前订单产品信息*/
			OrderProduct orderProduct = JSON.parseObject(jsonObject.toJSONString(),OrderProduct.class);
			String modifyTag = orderProduct.getModifyTag();
			if(StringUtils.isEmpty(modifyTag)){
				throw new UserException(ResultEnum.PARAM_ERROR);
			}
			/*生成产品实例编码*/
			if(orderProduct.getProdInstId() == null){
				Long id = sequenceService.getSequence("seq_prod_inst_id");
				orderProduct.setProdInstId(id);
				result.put(TableIdDefineUtils.PROD_INST_ID,id);
			}else{
				result.put(TableIdDefineUtils.PROD_INST_ID,orderProduct.getProdInstId());
			}
			/*处理orderId*/
			if(orderProduct.getOrderId() == null){
				if(!result.containsKey(TableIdDefineUtils.ORDER_ID) || StringUtils.isEmpty(result.getString(TableIdDefineUtils.ORDER_ID))){
					if(modifyTag.equals(Constant.ADD)){
						throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"订单产品信息orderId不存在！");
					}
					throw new UserException(ResultEnum.ORDER_INFO_ERROR);
				}else{
					orderProduct.setOrderId(result.getLong(TableIdDefineUtils.ORDER_ID));
				}
			}
			/*处理custId*/
			if(orderProduct.getCustId() == null){
				if(!result.containsKey(TableIdDefineUtils.CUST_ID) || StringUtils.isEmpty(result.getString(TableIdDefineUtils.CUST_ID))){
					if(modifyTag.equals(Constant.ADD)){
						throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"订单产品信息orderId不存在！");
					}
					throw new UserException(ResultEnum.ORDER_INFO_ERROR);
				}else{
					orderProduct.setCustId(result.getLong(TableIdDefineUtils.CUST_ID));
				}
			}
			if(modifyTag.equals(Constant.ADD)){
				orderProduct.setBeginDate(currentDate);
				orderProduct.setEndDate(DateUtils.parseDate(Constant.END_DATE));
			}else if(modifyTag.equals(Constant.UPDATE)){
				if(orderProduct.getProdInstId() != null){
					BsProduct bsProduct = bsProductMapper.getBsProductByPk(orderProduct.getProdInstId());
					if(bsProduct != null ){
						OrderProduct orderProductOld = JSON.parseObject(JSON.toJSONString(bsProduct),OrderProduct.class);
						logger.debug("旧节点信息："+JSON.toJSONString(bsProduct));
						orderProductOld.setEndDate(currentDate);
						orderProductOld.setUpdateTime(currentDate);
						orderProductOld.setUpdateUser(json.getLong("userId"));
						orderProductOld.setOrderId(result.getLong(TableIdDefineUtils.ORDER_ID));

						productArray.add(JSON.parseObject(JSON.toJSONString(orderProductOld)));
					}
				}else{
					throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"当前节点nodeId不存在！");
				}

				/*新信息*/
				orderProduct.setBeginDate(currentDate);
				orderProduct.setEndDate(DateUtils.parseDate(Constant.END_DATE));
				orderProduct.setUpdateTime(currentDate);
				orderProduct.setUpdateUser(json.getLong("userId"));
				orderProduct.setModifyTag(Constant.ADD);
			}else if(modifyTag.equals(Constant.DEL)){
				orderProduct.setEndDate(DateUtils.parseDate(Constant.END_DATE));
				//jsonObject.put("endDate",Constant.END_DATE);
			}
			productArray.add(orderProduct);
			jsonObject.put(OrderNodeDefineUtils.ORDER_PRODUCT,productArray);
		}
		return jsonObject;
	}

	private void validation(OrderProduct account){

	}
}
